package com.btpj.jetpack.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import org.koin.androidx.viewmodel.ext.android.getViewModel
import kotlin.reflect.KClass

/**
 * 注入ViewModel和DataBinding的Activity基类
 *
 * @author LTP 2020/7/2
 */
abstract class BaseActivity<VM : BaseViewModel, B : ViewDataBinding> : AppCompatActivity() {

    lateinit var mViewModel: VM
    lateinit var mBinding: B

    /** Activity的布局ID */
    abstract fun getLayoutId(): Int

    /** View初始化相关 */
    abstract fun initView()

    /** 重写实现LiveData监听逻辑 */
    open fun createObserve() {}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        StatusBarUtil.setImmersionStatus(this)
        initViewModel()
        initDataBinding()
        initView()
    }

    /**
     * 初始化ViewModel相关
     */
    private fun initViewModel() {
        val clazz =
            this.javaClass.kotlin.supertypes[0].arguments[0].type!!.classifier!! as KClass<VM>
        mViewModel = getViewModel(clazz)
        createObserve()
        mViewModel.start()
    }

    /**
     * 初始化DataBinding相关
     */
    private fun initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, getLayoutId())
        // dataBinding绑定lifecycle
        mBinding.lifecycleOwner = this
    }
}